#include "applicationinfo.h"
#include "newspaper/newspapermanager.h"
#include "model/Resources.h"
#include "content/articlecontent.h"

#include <QtGui/QGuiApplication>
#include <QtGui/QScreen>
#include <QDateTime>
#include <QDebug>


ApplicationInfo::ApplicationInfo(QObject *parent) :
    QObject(parent)
{
    m_isMobile = false;
#if defined(Q_OS_ANDROID) || defined(Q_OS_IOS) || defined(Q_OS_BLACKBERRY)
    m_isMobile = true;
#endif

    qDebug()<< " @@@ ApplicationInfo is mobile " << m_isMobile ;
    m_colors = new QQmlPropertyMap(this);
    m_colors->insert(QLatin1String("white"), QVariant("#ffffff"));
    m_colors->insert(QLatin1String("smokeGray"), QVariant("#eeeeee"));
    m_colors->insert(QLatin1String("paleGray"), QVariant("#d7d6d5"));
    m_colors->insert(QLatin1String("lightGray"), QVariant("#aeadac"));
    m_colors->insert(QLatin1String("darkGray"), QVariant("#35322f"));
    m_colors->insert(QLatin1String("mediumGray"), QVariant("#5d5b59"));
    m_colors->insert(QLatin1String("doubleDarkGray"), QVariant("#1e1b18"));
    m_colors->insert(QLatin1String("blue"), QVariant("#14aaff"));
    m_colors->insert(QLatin1String("darkBlue"), QVariant("#14148c"));

    m_constants = new QQmlPropertyMap(this);
    m_constants->insert(QLatin1String("isMobile"), QVariant(m_isMobile));
    m_constants->insert(QLatin1String("errorLoadingImage"), QVariant(tr("Error loading image - Host not found or unreachable")));


    QRect rect = qApp->primaryScreen()->geometry();
    qDebug()<< " @@@ ApplicationInfo is mobile " << rect.width() << " "<< rect.height();
    m_ratio = m_isMobile ? qMin(qMax(rect.width(), rect.height())/800. , qMin(rect.width(), rect.height())/480.) : 1;
    m_applicationWidth = m_isMobile ? rect.width() : 1120;

    m_sourceInfos = new SourceListModel(this);
    m_mapCategoryId2Articles =new QMap<int, ArticleListModel*>();
    m_categoryListModel = new CategoryListModel(this);
    m_contentModel = new ContentModel(this);

    m_currentSourceId = -1;
    m_isHasUpdateMoreArticle = true;
    m_updateContentSuccess = false;
}

void ApplicationInfo::notifyPortraitMode()
{
    int width = qApp->primaryScreen()->geometry().width();
    int height = qApp->primaryScreen()->geometry().height();
    setIsPortraitMode(height > width);
}

void ApplicationInfo::setIsPortraitMode(const bool newMode)
{
    if (m_isPortraitMode != newMode) {
        m_isPortraitMode = newMode;
        emit portraitModeChanged();
    }
}

void ApplicationInfo::setApplicationWidth(const int newWidth)
{
    if (newWidth != m_applicationWidth) {
        m_applicationWidth = newWidth;
        emit applicationWidthChanged();
    }
}

void ApplicationInfo::initData()
{

    connect (NewspaperManager::instance(),
             &NewspaperManager::hasDpiScreen,
             this,
             &ApplicationInfo::onHasDpiScreen);

    connect (NewspaperManager::instance(),
             &NewspaperManager::finishGetCategorySourceInfo,
             this,
             &ApplicationInfo::onFinishGetSourceInfo);

    connect (NewspaperManager::instance(),
             &NewspaperManager::addArticleListByCategoryChanged,
             this,
             &ApplicationInfo::onAddListArticleByCategory);

    connect (NewspaperManager::instance(),
             &NewspaperManager::addArticleListByCategoryMoreChanged,
             this,
             &ApplicationInfo::onAddListArticleByCategoryMoreChanged);

    connect (NewspaperManager::instance(),
             &NewspaperManager::addArticleListByCategoryNewChanged,
             this,
             &ApplicationInfo::onAddListArticleByCategoryNewChanged);

    connect (NewspaperManager::instance(),
             &NewspaperManager::updateArticleContentSuccessFull,
             this,
             &ApplicationInfo::onUpdateContentArticleResponse);

    connect (NewspaperManager::instance(),
             &NewspaperManager::isHasUpdateMoreArticle,
             this,
             &ApplicationInfo::onIsHasUpdateMoreArticle);

    connect (NewspaperManager::instance(),
             &NewspaperManager::openingUpdateSuccess,
             this,
             &ApplicationInfo::onOpeningUpdateSuccess);

    NewspaperManager::instance()->init();

}
void ApplicationInfo::onOpeningUpdateSuccess()
{
    emit openingUpdateSuccess();

    qDebug() << "void ApplicationInfo::onOpeningUpdateSuccess()";
}

void ApplicationInfo::onHasDpiScreen(QString dpi)
{
    if (dpi == "ldpi") {
        m_dpi = "mdpi";
    } else {
        m_dpi = dpi;
    }

    emit dpiChanged();
}

void ApplicationInfo::onFinishGetSourceInfo()
{

    m_sourceInfos->setSourceInfo(NewspaperManager::instance()->getListSourceInfoDefault());

    // add them source
    SourceInfo sourceI(-1,"Them Nguon Tin", QUrl(""),QUrl(""),"qrc:/image/resouces/images/drawable-hdpi/icon_docbao.png");

    m_sourceInfos->addSourceInfo(sourceI);

}

ArticleListModel* ApplicationInfo::getActicleListModel( int idCategory)
{
    QMap<int, ArticleListModel*>::iterator itr = m_mapCategoryId2Articles->find(idCategory);
    if(itr != m_mapCategoryId2Articles->end())
    {
        return itr.value();
    }
    return NULL;
}

ContentModel* ApplicationInfo::getContentModel()
{
    return m_contentModel;
}

//--------------------------------------------------------------------------------
/*
 * Display List Article by Category {Tong hop, the thao, chon loc, ....}
 *
 */

void ApplicationInfo::onAddListArticleByCategory(CategoryDetail* aCategoryDetail)
{
    if(m_currentSourceId == -1){
        m_currentSourceId = aCategoryDetail->idSource();
    }
    if(m_currentSourceId != aCategoryDetail->idSource())
    {
        // khac source
        m_currentSourceId = aCategoryDetail->idSource();
        m_categoryListModel->clear();
        m_mapCategoryId2Articles->clear();

    }
    QList<Article*> listArticles = aCategoryDetail->listArticleData();
    ArticleListModel* m_currentArticle = new ArticleListModel(this);

    m_currentArticle->setListArticle(listArticles);
    m_mapCategoryId2Articles->insert(aCategoryDetail->idCategory(), m_currentArticle);
    m_categoryListModel->addSourceInfo(aCategoryDetail->idCategory());
}

void ApplicationInfo::onSourceClick(int souceId)
{
    Q_UNUSED(souceId);////
}

void ApplicationInfo::onUpdateMoreCategoryRequest(int countCategoryCurrent)
{
    qDebug() << "update more category: " << countCategoryCurrent;
    int maxcategory = NewspaperManager::instance()->getSizeCategorysCurrentSource();
    if(maxcategory <= countCategoryCurrent)
    {
        qDebug() << "category full" ;
    }

    int categoryId = NewspaperManager::instance()->getCategoryIdByIndexCurrentSource(countCategoryCurrent);
    if(categoryId >= 0 ) {
        NewspaperManager::instance()->getUpdateMoreCategory(categoryId);
    }

}

void ApplicationInfo::onUpdateNewArticleRequest(int categoryId)
{
    NewspaperManager::instance()->getUpdateNewArticle(categoryId);
}

void ApplicationInfo::onUpdateMoreArticleRequest(int categoryId)
{
    NewspaperManager::instance()->getUpdateMoreArticle(categoryId);
}

void ApplicationInfo::onAddListArticleByCategoryMoreChanged(CategoryDetail *aCategoryDetail, int cid)
{

    ArticleListModel* articlesModel = getActicleListModel(cid);
    QList<Article*> listArticlesMore= aCategoryDetail->listArticleData();

    if(articlesModel)
    {

        for ( int i=0; i< listArticlesMore.length(); i++) {
            Article* article = listArticlesMore.at(i);
            articlesModel->addArticleItem(article);
        }

    } else
    {
        //articlesModel = new ArticleListModel(this);
        //articlesModel->setListArticle(listArticlesMore);

    }
}

void ApplicationInfo::onAddListArticleByCategoryNewChanged(CategoryDetail *aCategoryDetail, int cid)
{
    if(aCategoryDetail->idSource() != m_currentSourceId){
        qDebug() << "ApplicationInfo::onAddListArticleByCategoryNewChanged " << "khac source id" ;
        return ;
    }

    ArticleListModel* articlesModel = getActicleListModel(cid);
    QList<Article*> listArticlesMore= aCategoryDetail->listArticleData();

    if(articlesModel)
    {

        for ( int i=0; i< listArticlesMore.length(); i++) {
            Article* article = listArticlesMore.at(i);
            articlesModel->insertArticleItem(article,0);
        }

    } else
    {
        //articlesModel = new ArticleListModel(this);
        //articlesModel->setListArticle(listArticlesMore);

    }
}

void ApplicationInfo::onOpenContentArticleDetailRequest(const int idCategory, const int articleId)
{
    NewspaperManager::instance()->getUpdateAticleContent(idCategory, articleId);
}

void ApplicationInfo::onUpdateContentArticleResponse(Article *article)
{

    QDateTime dateTime;
    dateTime.setMSecsSinceEpoch(article->posttime());
    int subTime =  qAbs(QDateTime::currentDateTime().time().secsTo(dateTime.time()));

    QString time;
    if ( subTime / 3600 > 0) {
        time = QVariant(subTime / 3600).toString() + " giờ trước";
    } else {
        time = QVariant(subTime / 60).toString() + " phút trước";
    }

    QString title = article->title();
    SourceInfo sourceInfo = NewspaperManager::instance()->getSourceInfo(article->sid());

    QString linkSourceDomain = NewspaperManager::instance()->simageDomain();

    linkSourceDomain.append("/");
    linkSourceDomain.append( NewspaperManager::instance()->dpiScreen());
    linkSourceDomain.append("/");
    linkSourceDomain.append(sourceInfo.urlLink().toString());
    linkSourceDomain.append(".png");

    qDebug() << "link source Domain Icon : " << linkSourceDomain;

    ArticleContent articleContent =  ArticleContent(article);
    QList < TextData > listData = articleContent.listData();

    m_contentModel->setContentArticle(listData);

    m_currentTitleArticle = title;
    emit currentTitleArticleChanged();

    m_currentTimeArticle = time;
    emit currentTimeArticleChanged();

    m_currenLinkSourceDomainArticle = linkSourceDomain;
    emit currenLinkSourceDomainArticleChanged();

    m_currentSourceInfoArticle = sourceInfo.name();
    emit currentSourceInfoArticleChanged();

    m_updateContentSuccess = true;
    emit updateContentSuccessChanged();

}

void ApplicationInfo::onIsHasUpdateMoreArticle(bool check)
{
    m_isHasUpdateMoreArticle = check;
    emit isHasUpdateMoreArticleChanged();
}

void ApplicationInfo::changeSource(const int sourceId)
{
    NewspaperManager::instance()->changeCurrentSourceDetail(sourceId);

}
